import { useTranslation } from 'react-i18next';
import { Image, Input, Toast } from 'antd-mobile';
import { useCallback, useEffect, useState } from 'react';
import getAssetsFile from '@/utils/pub-use';
import HeaderComponent from '@/components/HeaderComponent/HeaderComponent';
import { swap, getApiToken, swapEnum, getCurrencyList } from '@/api/module/U2U';
import { useAppSelector } from '@/hooks/useAppSelector';
import { debounce } from 'lodash';
import { CenterPopupComponent } from '@/components/CenterPopupComponent/CenterPopupComponent';
import { BanlanceType } from '@/api/module/user';
import { useNavigate } from 'react-router-dom';
const AssetsComponent = () => {
  const { t } = useTranslation();
  const userInfo = useAppSelector((state) => state.userInfo.userInfo);
  const assetsList = [
    {
      image: getAssetsFile('home/third.png'),
      title: 'USDT',
      key: 'USDT',
    },
    {
      image: getAssetsFile('home/sixth.png'),
      title: 'RegisterBeans',
      key: 'ZCB',
    },
    {
      image: getAssetsFile('home/fourth.png'),
      title: 'CashBeans',
      key: 'XJB',
    },
  ];
  return (
    <div>
      <div className="flex items-center justify-between asstest mx-2 bg-bg-1 py-5 px-4 rounded-xl pb-6 mt-4">
        <div className="left">
          <div className="opacity-50 text-xs">{t('bugRate')}</div>
          <div className="font-bold text-2xl mt-1">$1</div>
        </div>
        <div className="relative right flex items-center">
          <Image
            className="absolute left-0 bg-font-2 p-2 rounded-full"
            src={getAssetsFile('u2u/person-icon.png')}
            width={32}
            height={32}
            alt=""
          />
          <span className="bg-white-7 pl-10 pr-4 rounded-full text-font-2 font-semibold">
            {userInfo.level_name}
          </span>
        </div>
      </div>
      <div className="value text-white-1 py-5 px-4 bg-custom-gradient-1 rounded-xl relative -top-4 flex items-center justify-between">
        {assetsList.map((item) => {
          return (
            <div>
              <Image src={item.image} width={32} height={32} alt="" />
              <div className="text-xs opacity-50 mt-2">{t(item.title)}</div>
              <div className="font-bold text-xl mt-1">
                {
                  (userInfo[item.key as keyof typeof userInfo] as BanlanceType)
                    .balance
                }
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

const FormComponent = () => {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const [register, setRegister] = useState('');
  const [usdt, setUsdt] = useState('');
  const [opt, setOpt] = useState('');
  const [visible, setVisible] = useState(false);
  const [APIToken, setAPIToken] = useState('');
  const [currencyList, setCurrencyList] = useState<
    Awaited<ReturnType<typeof getCurrencyList>>['data']
  >({
    list_sale: [],
    list_buy: [],
  });
  const reqSwap = async (type: swapEnum) => {
    try {
      Toast.show({
        icon: 'loading',
      });
      const res = await swap({
        action: type,
        currency_cost: 'USDT',
        currency_buy: 'ZCB',
        currency_main: 'USDt',
        amount: register,
        password: opt,
        APITOKEN: APIToken,
      });
      Toast.clear();
      setAPIToken('');
      Toast.show({ content: res.msg });
      if (res.code == 0) {
        setRegister('');
        setUsdt('');
        setOpt('');
      }
      if (res.code == 1) {
        navigate('/updatePassword');
      }
    } catch (error) {
      Toast.clear();
      setAPIToken('');
    }
  };
  const calculate = useCallback(
    debounce(async function (val) {
      try {
        if (!val) {
          setUsdt('');
          return;
        }
        Toast.show({
          icon: 'loading',
        });
        const res = await swap({
          action: swapEnum.calculate,
          currency_cost: 'USDT',
          currency_buy: 'ZCB',
          currency_main: 'ZCB',
          amount: val,
        });
        Toast.clear();

        if (res.code == 0) {
          if (!res.data.balance_status) {
            Toast.show({
              content: t('balanceInsufficient'),
            });
          } else {
            if (res.data.calculate.error_code == 0) {
              setUsdt(res.data.calculate.receive_amount + '');
            } else {
              Toast.show({
                content: t('QuantityIncorrect'),
              });
              setUsdt('');
            }
          }
        } else {
          Toast.show({
            content: res.msg,
          });
          setUsdt('');
        }
      } catch (error) {
        setUsdt('');
        Toast.clear();
      }
    }, 300),
    []
  );
  const reqApiToken = async () => {
    try {
      if (!register || !opt) {
        Toast.show({
          content: t('enterCompleteInformation'),
        });
        return;
      }
      if (!APIToken) {
        const res = await getApiToken();
        setAPIToken(res.data.api_token);
      }

      setVisible(true);
    } catch (error) {
      console.log(error);
    }
  };
  const reqCurrencyList = async () => {
    try {
      const res = await getCurrencyList('usdt');
      console.log(res);
      res.code == 0 && setCurrencyList(res.data);
    } catch (error) {
      console.log(error);
    }
  };
  useEffect(() => {
    reqCurrencyList();
  }, []);
  return (
    <div
      style={{
        fontSize: '95%',
      }}
    >
      <div className="register">
        <div>{t('RegisterBeans')}</div>
        <Input
          style={{
            '--font-size': '14px',
            '--color': '#fff',
          }}
          className="bg-bg-1 py-4 mt-3 px-3 rounded-lg "
          placeholder={`${t('enter')}`}
          value={register}
          onChange={(val) => {
            setRegister(val);
            calculate(val);
          }}
        />
        <div className="text-right mt-2 opacity-50">
          <span>
            {t('minimum')}: {currencyList.list_sale[0]?.min_buy}
          </span>
        </div>
      </div>
      <div className="USDT mt-4 ">
        <div>{t('USDT')}</div>
        <Input
          readOnly
          style={{
            '--font-size': '14px',
            '--color': '#fff',
          }}
          className="bg-bg-1 py-4 mt-3 px-3 rounded-lg "
          placeholder={`${t('enter')}`}
          value={usdt}
        />
      </div>
      <div className="opt mt-4">
        <div>{t('password')}</div>
        <Input
          style={{
            '--font-size': '14px',
            '--color': '#fff',
          }}
          type="password"
          className="bg-bg-1 py-4 mt-3 px-3 rounded-lg "
          placeholder={`${t('enter')}`}
          value={opt}
          onChange={(val) => {
            setOpt(val);
          }}
        />
      </div>
      <div
        onClick={() => reqApiToken()}
        className="mt-6 bg-bg-16 py-4 rounded-md text-center text-base"
      >
        {t('buy')}
      </div>

      <CenterPopupComponent
        visible={visible}
        setVisible={setVisible}
        title={`${t('buy')}ZCB`}
        content={
          <div>
            <div>
              {t('consume')}: {usdt}USDT
            </div>
            <div>
              {t('obtain')}: {register}
              {t('ZCB')}
            </div>
          </div>
        }
        onClick={() => reqSwap(swapEnum.swap)}
      />
    </div>
  );
};
export default function Buy() {
  // i18n.changeLanguage('en');
  // const { t, i18n } = useTranslation();
  // const changeI18n = () => {
  //   i18n.changeLanguage(i18n.language == 'en' ? 'zh' : 'en');
  // };
  return (
    <div className="text-white-1 px-3 pb-28">
      <HeaderComponent title="buy" />
      <AssetsComponent />
      <FormComponent />
      {/* <span>{t('U2U')}</span>
      <button onClick={() => changeI18n()}>asd</button> */}
    </div>
  );
}
